<template>
  <div>
    <el-image v-show="img !== undefined" @click="bigImg(`${img}`)" class="main-img" :src="img" :preview-src-list="srcList">
    </el-image>
    <el-button v-show="img !== undefined" icon="el-icon-delete" class="wrong_class" @click="handleDelete()" />
    <div v-show="img === undefined" class="main-head" @click="editCropper()">+</div>
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body @opened="modalOpened"  @close="closeDialog">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <vue-cropper
            ref="cropper"
            :img="img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <div class="logo-upload-preview">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { uploadMainImg } from "@/api/product/list";
import { VueCropper } from "vue-cropper";
import { debounce } from '@/utils'

export default {
  components: { VueCropper },
  props: {
    product: {
      type: Object
    },
    setWidth:{
      type:Number,
      default:800
    },
    setHeight:{
      type:Number,
      default:518
    },
  },
  data() {
    return {
      
      // 是否显示弹出层
      open: false,
      // 是否显示cropper
      visible: false,
      // 图片URL
      img: undefined, //裁剪图片的地址
      srcList:["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"],
      previews: {},
      resizeHandler: null,
      options: {
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.setWidth / 2, // 默认生成截图框宽度
        autoCropHeight: this.setHeight / 2, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        outputType:"png", // 默认生成截图为PNG格式
        //enlarge:1,//图片根据截图框输出比例倍数
      },
      title: "上传图片",
    };
  },
  watch: {
    product: {
      immediate: true,
      handler: function() {
        if (this.product.mainImg !== undefined && this.product.mainImg !== '') {
          this.img = process.env.VUE_APP_BASE_API + this.product.mainImg;
        } else {
          this.img = undefined;
        }
      }
    },
  },
  methods: {
    // 编辑头像
    editCropper() {
      this.open = true;
    },
    handleDelete() {
      this.img = undefined;
      this.$emit('saveFile', undefined);
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true;
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    // 刷新组件
    refresh() {
      this.$refs.cropper.refresh();
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.img = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData(); 
        formData.append('mainImg', data);
        uploadMainImg(formData).then(response => {
          this.open = false;
          let imgUrl = response.imgUrl;
          this.img = process.env.VUE_APP_BASE_API + imgUrl;
          this.$emit('saveFile', imgUrl);
          this.$modal.msgSuccess("上传成功");
          this.visible = false;
        });
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.visible = false;
      window.removeEventListener("resize", this.resizeHandler)
    },
    bigImg(url) {
      this.srcList[0] = url;
    },
  }
};
</script>

<style scoped lang="scss">

.main-head {
  display: inline-block;
  width: 120px;
	height: 120px;
  position: absolute;
  margin-left: 20px;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  line-height: 120px;
  text-align: center;
}

.main-img {
  width: 120px; 
  height: 120px; 
  margin-bottom:-4px;
  margin-left: 20px;
}

.wrong_class {
  width: 5px; 
  height: 5px; 
  float:right;
  margin-left: -30px;
  border: 0;
  position: absolute;
  z-index:999;
}
</style>
